package com.example.mybank.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mybank.entity.Account;
import com.example.mybank.entity.Users;
import com.example.mybank.mapper.AccountMapper;
import com.example.mybank.springSecurity.UserHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    AccountMapper accountMapper;

    /**
     * 管理员获取所有账户信息
     * @return
     */
    @GetMapping("/all")
    public List<Account> getAll(){
        return accountMapper.selectList(null);
    }


    // 用户：获得自己的账户
    @GetMapping("/{userID}")
    public List<Account> getByUser(@PathVariable("userID") int userID){
        QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users",userID);
        return accountMapper.selectList(queryWrapper);
    }


    /**
     * 用户注册账户
     * @param account
     * @return
     */
    @PostMapping("/register")
    public Boolean registerAccount(@RequestBody Account account){
        account.setIs_bank(false);

        UserHandler principal = (UserHandler) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Users users = principal.getUsers();

        account.setUsers(users.getId());
        accountMapper.insert(account);
        return true;
    }



}
